package com.ias.agdis_r.adapter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.ias.agdis_r.R;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.util.sdcard.SDcard;
import com.ias.agdis_r.util.sdcard.WriteLog;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 *	zhangsc
 * */
public class PhotoAdapter extends BaseAdapter {
	private List<File> list = new ArrayList<File>();
	private Context context = null; 
	private LayoutInflater inflater = null;  
	private HashMap<Integer, Boolean> checkstate = new HashMap<Integer, Boolean>();
	public static final String END_PRE = ".jpg";
	private boolean checkable = false;  //能否选择标识
	public void setCheckable(boolean checkable){
		this.checkable = checkable;
		if(!checkable)
		{
			diselectAll();
		}
	}
	public boolean isCheckable(){
		
		return this.checkable;
	}
	public PhotoAdapter(Context context){
		this.context = context;
		init();
	}
	@Override
	public int getCount() {
		return list.size();
	}
	
	@Override
	public File getItem(int ps) {
		return list.get(ps);
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}
	
	public void update()
	{
		init();
		notifyDataSetInvalidated();
	}
	
	public void init(){
		list.clear();
		checkstate.clear();
		File path = new File(DataBaseManager.PHOTO_FORDER_PATH);
		File[] file = path.listFiles(new CFileFilter());
		// file可能为空.
		if (file != null) {
			int length = file.length;
			for (int i = 0; i < length; i++) {
				checkstate.put(i, false);
				list.add(file[i]);
			}
		}
	}
	public int getItemSize(){

		return list.size();
	}

	public void selectAll(){
		int length = checkstate.size();
		for(int i = 0; i < length; i++){
			checkstate.put(i, true);
		}
		notifyDataSetInvalidated();
	}
	
	public void select(int postion,View view){
		if(this.checkable)
		{
			//反选
			boolean flag = !checkstate.get(postion);
			checkstate.put(postion, flag);
			
			TextView photo_name = (TextView)view.findViewById(R.id.txt_photo_name);
			ImageView check = (ImageView)view.findViewById(R.id.img_check);
			if(flag){
				photo_name.setTextColor(context.getResources().getColor(R.color.green));
				check.setVisibility(View.VISIBLE);
			} else {
				
				photo_name.setTextColor(context.getResources().getColor(R.color.black));
				check.setVisibility(View.GONE);
			}
		}
	}
	
	public void diselectAll(){
		int length = checkstate.size();
		for(int i = 0; i < length; i++){
			checkstate.put(i, false);
		}
		notifyDataSetInvalidated();
	}
	
	public boolean hasCheckItem(){

		int length = checkstate.size();
		for(int i = 0; i < length; i++){
		
			boolean checked = checkstate.get(i);
			if(checked)
			{
				return true;
			}
		}
		
		return false;
	}

	public List<File> getSelectImage(){

		List<File> fileList = null;
		if(!hasCheckItem())
		{
			return null;
		}else{
			fileList = new ArrayList<File>();
		}
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
				context.getString(R.string.uploadPicture2), false);
		int length = checkstate.size();
		for(int i = 0; i < length; i++) {
			boolean checked = checkstate.get(i);
			if (checked) {
				//删除照片文件
				File file = list.get(i);
				fileList.add(file);
			}
		}
		return fileList;
	}
	/**
	 * 删除选中的图片
	 */
	public void deleteImage()
	{
		if(!hasCheckItem())
		{
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
					context.getString(R.string.choosePicture), false);
			return;
		}

		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
				context.getString(R.string.deletePicture2), false);
		int length = checkstate.size();
		for(int i = 0; i < length; i++){
			boolean checked = checkstate.get(i);
			if(checked)
			{
				//删除照片文件
				File file = list.get(i);
				if(file!=null&&file.exists())
				{
					WriteLog.getInstance().writeLog(context.getString(R.string.deleteLocalPicture) + file.getPath());
					file.delete();
				}
				
				//删除缩略图
				String path = file.getPath();
				String thumbnails_path = path.replace(DataBaseManager.PHOTO_FORDER_PATH, DataBaseManager.DCIM_FORDER_PATH); 
				File thumbnails_file = new File(thumbnails_path);
				if(thumbnails_file!=null&&thumbnails_file.exists())
				{
					thumbnails_file.delete();
				}
			}
		}
		init();
		notifyDataSetInvalidated();
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = new ViewHolder();
		if(null == convertView){
			inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(R.layout.item_photo_grid, null);
			holder.photo_thumbnails = (ImageView)convertView.findViewById(R.id.photo_thumbnails);
			holder.check = (ImageView)convertView.findViewById(R.id.img_check);
			holder.photo_name = (TextView)convertView.findViewById(R.id.txt_photo_name);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder)convertView.getTag();
		}
		if(checkstate.get(position)){
			holder.photo_name.setTextColor(context.getResources().getColor(R.color.green));
			holder.check.setVisibility(View.VISIBLE);
		} else {
			
			holder.photo_name.setTextColor(context.getResources().getColor(R.color.black));
			holder.check.setVisibility(View.GONE);
		}
		Bitmap bitmap = getThumbnails(list.get(position).getPath());
		if(bitmap!=null)
		{
			holder.photo_thumbnails.setImageBitmap(bitmap);
		}
		else
		{
			holder.photo_thumbnails.setImageDrawable(context.getResources().getDrawable(R.drawable.format_img_broken));
		}
		holder.photo_name.setText(list.get(position).getName());
		return convertView;
	}
	
	/**
	 * 获取缩略图
	 * @param path
	 * @return
	 */
	private Bitmap getThumbnails(String path)
	{
		Bitmap bitmap = null; 
		try {
			
			String thumbnails_path = path.replace(DataBaseManager.PHOTO_FORDER_PATH, DataBaseManager.DCIM_FORDER_PATH); 
			BitmapFactory.Options options = new BitmapFactory.Options();  
			options.inJustDecodeBounds = false; // 设为 false
			bitmap = BitmapFactory.decodeFile(thumbnails_path, options); 
			//如果没有缩略图
			if(bitmap==null)
			{	
				//生成缩略图
				bitmap = makeThumbnails(path,thumbnails_path);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return bitmap;
	}
	
	/**
	 * 保存照片缩略图
	 */
	private Bitmap makeThumbnails(String path,String thumbnails_path)
	{
		Bitmap bitmap = null;  
		BufferedOutputStream bos = null;
        try {
			BitmapFactory.Options options = new BitmapFactory.Options();  
			options.inJustDecodeBounds = true;  
			// 获取这个图片的宽和高，注意此处的bitmap为null  
			bitmap = BitmapFactory.decodeFile(path, options);  
			options.inJustDecodeBounds = false; // 设为 false  
			// 计算缩放比  
			int h = options.outHeight;  
			int w = options.outWidth;  
			int beWidth = w / 90;  
			int beHeight = h / 90;  
			int be = 1;  
			if (beWidth < beHeight) {  
			    be = beWidth;  
			} else {  
			    be = beHeight;  
			}  
			if (be <= 0) {  
			    be = 1;  
			}  
			options.inSampleSize = be;  
			// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false  
			bitmap = BitmapFactory.decodeFile(path, options); 
			//如果目录不存在创建目录
			if (!SDcard.isFileExist(DataBaseManager.DCIM_FORDER_PATH)) 
			{
				SDcard.creatSDDir(DataBaseManager.DCIM_FORDER_PATH);
			}
			//生成缩略图
			if (!SDcard.isFileExist(thumbnails_path))
			{

				SDcard.creatSDFile(thumbnails_path);
			}
			bos = new BufferedOutputStream(new FileOutputStream(thumbnails_path));
			//OutputStream os = new FileOutputStream(myCaptureFile);		
			/* 采用压缩转档方法 */						
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			/* 调用flush()方法，更新BufferStream */						
			bos.flush();
						
			/* 结束OutputStream */						
			bos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        finally{
        	if(bos!=null)
        	{
        		try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        }
		
        return bitmap;  
	}
	private class ViewHolder{
		ImageView photo_thumbnails;
		ImageView check;
		TextView photo_name;
	}
	
	private class CFileFilter implements FileFilter{
		@Override
		public boolean accept(File pathname) {
			boolean isEnd = pathname.getName().endsWith(END_PRE);
			return isEnd;
		}
		
	}
}
